//
//  StoryLibraryView.m
//  iPing
//
//  Created by Thomas on 8/11/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "StoryLibraryView.h"

#import "TCSGStory.h"
#import "TCSGBrowserView.h"


@implementation StoryLibraryView
#define kSGLTagAll		0
#define kSGLTagTitle    1
#define kSGLTagAuthor	2
#define	kSGLTagGenre	3

-(void)setAddedObjects:(NSArray *)toAddedObjects;
{
	addedObjects = nil;
	addedObjects = [[NSMutableArray alloc] init];

	addedObjects = toAddedObjects;
}
-(IBAction)removeSelected:(id)sender
{
	//[myController remove:[myController selectedObjects]];
	int i;
	for(i=0;i<[[myController selectedObjects] count];i++)
	{
		TCSGStory *theID= [[myController selectedObjects] objectAtIndex:i];
		NSLog(@"%@",theID.HTMLCode);
		//[managedObjectContext deleteObject:theID];
		[TCSGStory removeObjectForHTMLCode:theID.HTMLCode inContext:managedObjectContext];
		[tableView reloadData];
		[myController removeObject:theID];
		
	}
	if([managedObjectContext hasChanges])
	{
		NSLog(@"has Changes");
	}
	[managedObjectContext commitEditing];
	NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        [[NSApplication sharedApplication] presentError:error];
    }
	
}

- (void)awakeFromNib
{
	/*NSString *string = [NSString stringWithContentsOfFile:@"/Users/tom/Desktop/Untitled.rtf"];
	NSLog(@"string: %@",string);
	[summaryTextField setString:string];
	NSLog(@"font attributes: %@",[[[summaryTextField font] fontDescriptor] fontAttributes]);*/
	db = [[TCSGdatabaseList alloc] init];
	
	[tableView reloadData];
	[summaryTextField setString:@""];
		
	// setting Notifications Observers;
	[[NSNotificationCenter defaultCenter] addObserver:self 
           selector:@selector(addToController) 
               name:@"hellotoo"
             object:nil]; 
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(showInFinder:) 
												 name:MENUNOTIFICATION
											   object:nil]; 
	
	//Setting Sort Descriptors For Array
	NSSortDescriptor * sd = [[NSSortDescriptor alloc] initWithKey:@"author" ascending:YES];
	NSSortDescriptor * sd2 = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
	
	[myController setSortDescriptors:[NSArray arrayWithObjects:sd,sd2,nil]];
	
	[sd release];
	[sd2 release];

}

- (void) setsearchCategory:(int)tag
{
	searchCategory = tag;
}
- (void)searchWithString:(NSString *)string
{
	if([string isEqualToString:@""])
	{
		[myController setFilterPredicate:nil];
	}
	else
	{
		NSPredicate *pred;
		switch(searchCategory)
		{
			case 0:
			{
				pred = [NSPredicate predicateWithFormat:@"(author contains[cd] %@) OR (title contains[cd] %@) OR (genre contains[cd] %@) or (host contains[cd] %@)",string,string,string,nil]; 
				break;
			}
			case kSGLTagTitle:
				pred = [NSPredicate predicateWithFormat:@"title contains[cd] %@",string];
				break;
			case kSGLTagAuthor:
				pred = [NSPredicate predicateWithFormat:@"author contains[cd] %@",string];
				break;
			case kSGLTagGenre:
				pred = [NSPredicate predicateWithFormat:@"genre contains[cd] %@",string];
				break;
				
		}
		[myController setFilterPredicate:pred];
	}
	
}
- (NSString *)getHTMLCode
{
	NSArray	*stories = [myController selectedObjects];
	TCSGStory *story = [stories objectAtIndex:0];
	NSString *code = story.HTMLCode;
	return code;
}
- (void)showInFinder:(NSNotification *)note
{
	if([[note object] isEqualToString:@"showInFinder"])
	{
		[[NSWorkspace sharedWorkspace] selectFile:[TCSGGeneralMethods fullStoryPathForHTMLCode:[self getHTMLCode]] inFileViewerRootedAtPath:@""];
	}
	if([[note object] isEqualToString:@"ePub"])
	{
		NSLog(@"convert epub");
		NSArray	*stories = [myController selectedObjects];
		TCSGStory *story = [stories objectAtIndex:0];
		//[[NSFileManager defaultManager] removeItemAtPath:[TCSGGeneralMethods epubPathForHTMLCode:[self getHTMLCode]] error:nil];
		NSString *inputPath=[TCSGGeneralMethods fullStoryPathForHTMLCode:[self getHTMLCode]];
		NSString *outputPath=[TCSGGeneralMethods epubPathForHTMLCode:[self getHTMLCode]];
		NSString *title=[NSString stringWithFormat:@"--title=\"%@\"",story.title];
		NSString *author=[NSString stringWithFormat:@"--authors=\"%@\"",story.author];
		NSArray *hello=[NSArray arrayWithObjects:inputPath,outputPath,title,author,nil];
		NSLog(@"hello: %@",hello);
		NSTask *task = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/ebook-convert" arguments:hello];
	}
}
-(IBAction)selectionDidChange:(id)sender
{
	//[tableView setTheMenu:contextMenu];
	NSArray	*stories = [myController selectedObjects];
	TCSGStory *story = [stories objectAtIndex:0];
	NSString *summaryText=[NSString stringWithFormat:@"%@\nBy: %@\n\n",story.title,story.author,nil];
	
	if(story.summary != nil && [story.summary length]!=0)
	{
		summaryText = [summaryText stringByAppendingString:[NSString stringWithFormat:@"Summary:\n%@\n\n",story.summary,nil]];
	}
	if(story.genre != nil && [story.genre length]!=0)
	{
		summaryText = [summaryText stringByAppendingString:[NSString stringWithFormat:@"Genre:\n%@\n\n",story.genre,nil]];
	}
	if(story.codes != nil && [story.codes length]!=0)
	{
		summaryText = [summaryText stringByAppendingString:[NSString stringWithFormat:@"Codes:\n%@\n\n",story.codes,nil]];
	}
	[summaryTextField setString:summaryText];
	[summaryText release];
}

#pragma mark tableView Delegate Methods

/*- (id)tableView:(NSTableView *)tv 
objectValueForTableColumn:(NSTableColumn *)tableColumn 
			row:(int)row 
{ 
	NSArray *columns = [NSArray arrayWithObjects:@"ID",@"Title",@"Author",@"check",@"Host",@"DL",@"lll",nil];
	long column = [columns indexOfObject:[tableColumn identifier]];
	NSDictionary *storyDict = [db getDictForRow:row];
	NSString *v;
	switch (column) {
		case 0:
			v=[storyDict objectForKey:IDKEY];
			break;
		case 1:
			v=[storyDict objectForKey:TITLEKEY];
			break;
		case 2:
			v=[storyDict objectForKey:AUTHORKEY];
			break;
		case 4:
			v=[storyDict objectForKey:HOSTKEY];
			break;
		case 5:
		{
			v=@"lll";
			break;
		}
		default:
			v=@"";
			break;
	}
    return v; 
} 
- (BOOL)tableView:(NSTableView *)tv 
  shouldTrackCell:(NSCell *)cell 
   forTableColumn:(NSTableColumn *)tableColumn 
			  row:(NSInteger)row
{
	//NSLog(@"tracking: %i",row);
	//NSLog(@"tracking: %@",[tableColumn identifier]);
	BOOL tracking = NO;
	/*if([[tableColumn identifier] isEqualToString:@"DL"])
	{
		tracking =YES;
		[theStoryListView switchCheck:CHECKKEY forRow:row];
		
	}
	return YES;
}

- (int)numberOfRowsInTableView:(NSTableView *)tv 
{ 
    return [db numberOfItems]; 
}

-(void) tableViewSelectionDidChange:(NSNotification *)aNotification
{
	NSLog(@"Selection Did Change in library View");
}





-(NSString *)tableView:(NSTableView *)aTableView 
		toolTipForCell:(NSCell *)aCell 
				  rect:(NSRectPointer)rect 
		   tableColumn:(NSTableColumn *)aTableColumn 
				   row:(NSInteger)row 
		 mouseLocation:(NSPoint)mouseLocation
{
	NSString *returnString=@"";
	if([[aTableColumn identifier] isEqualToString:@"DL"])
	{
		returnString = @"Determines if the Story Should be Compiled";
	}
	else
	{
		NSDictionary *tempDict = [db getDictForRow:row];
		//[tempDict writeToFile:@"/Users/tom/Desktop.plist" atomically:YES];
		if([[tempDict allKeys] containsObject:@"Summary"]){ returnString = [tempDict objectForKey:@"Summary"];/*NSLog(@"returnString: %@",[tempDict objectForKey:@"Summary"]);}
		else { returnString = @"Summary Not Available";}
	}
	return returnString;	
}*/
- (NSString *)applicationSupportFolder {
	
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
	NSLog(@"savePath: %@",[basePath stringByAppendingPathComponent:@"Story Grabber"]);
    return [[basePath stringByAppendingPathComponent:@"Story Grabber"] stringByAppendingPathComponent:@"Stories"];
}
#pragma mark SplitView delegates
- (BOOL)splitView:(NSSplitView *)sender canCollapseSubview:(NSView *)subview
{
	if(![sender isSubviewCollapsed:subview])
		return YES;
		
		
	return NO;
	
}
- (BOOL)splitView:(NSSplitView *)splitView shouldCollapseSubview:subview forDoubleClickOnDividerAtIndex:(NSInteger)dividerIndex
{
	
	int subviewTag = [subview tag];
	
	if((subviewTag == 1001 || subviewTag == 1002) && ![splitView isSubviewCollapsed:subview])
	{
		if([subview respondsToSelector:@selector(collapsed)])
		{
			[subview setCollapsed:YES];
			//[subview setDividerIndex:];
			return YES;
		}
		return YES;
	}
	
	return NO;
}

@end
